package org.jeecg.modules.basic.supplier.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.basic.customer.entity.BasicCustomer;
import org.jeecg.modules.basic.supplier.entity.BasicSupplier;
import org.jeecg.modules.basic.supplier.mapper.BasicSupplierMapper;
import org.jeecg.modules.basic.supplier.service.IBasicSupplierService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 供应商信息
 * @Author: jeecg-boot
 * @Date:   2023-07-25
 * @Version: V1.0
 */
@Service
public class BasicSupplierServiceImpl extends ServiceImpl<BasicSupplierMapper, BasicSupplier> implements IBasicSupplierService {

    @Autowired
    private ISysBaseAPI iSysBaseAPI;
    @Autowired
    private BasicSupplierMapper supplierMapper;

    /**
     * 导入
     * @param request
     * @return
     */
    @Override
    public Result<String> importExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<DictModel> dictList = iSysBaseAPI.getDictItems("supplier_type");
                List<String> types = dictList.stream().map(DictModel::getValue).collect(Collectors.toList());
                List<BasicSupplier> list = ExcelImportUtil.importExcel(file.getInputStream(), BasicSupplier.class, params);
                for (BasicSupplier supplier : list) {
                    if (StringUtils.isBlank(supplier.getName())) {
                        return Result.error("文件导入失败:供应商名称不能为空！");
                    }
                    if (StringUtils.isBlank(supplier.getType())) {
                        return Result.error("文件导入失败:供应商类型不能为空！");
                    }
                    if (!types.contains(supplier.getType())) {
                        return Result.error("文件导入失败:供应商类型填写错误！");
                    }
                    if (StringUtils.isBlank(supplier.getStatus())) {
                        return Result.error("文件导入失败:状态不能为空！");
                    }
                    if (!"0".equals(supplier.getStatus()) && !"1".equals(supplier.getStatus())) {
                        return Result.error("文件导入失败:状态只能填启用或禁用！");
                    }
                    List<BasicSupplier> names = this.list(new LambdaQueryWrapper<BasicSupplier>()
                            .eq(BasicSupplier::getName, supplier.getName()));
                    if (CollectionUtil.isNotEmpty(names)) {
                        return Result.error("文件导入失败:供应商名称 "+supplier.getName()+" 系统中已存在！");
                    }
                    Object result = FillRuleUtil.executeRule(FillRuleConstant.BASIC_CUSTOMER, new JSONObject());
                    supplier.setCode(result.toString());
                }
                this.saveBatch(list);
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
                if(msg!=null && msg.indexOf("Duplicate entry")>=0){
                    return Result.error("文件导入失败:有重复数据！");
                }else{
                    return Result.error("文件导入失败:" + e.getMessage());
                }
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 分页
     * @param page
     * @param unit
     * @return
     */
    @Override
    public Page<BasicSupplier> pageSupplier(Page<BasicSupplier> page, BasicSupplier unit) {
        List<BasicSupplier> list = supplierMapper.pageSupplier(page, unit);
        return page.setRecords(list);
    }
}
